package com.atjava.nebula.core.exception.config;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import com.atjava.nebula.core.exception.baseExp.XmlParseException;
import com.atjava.nebula.core.exception.bean.ExceptionInfo;

/**
 * 解析XML文件得到ExceptionInfo对象集合
 * */
public class ParseExpInfoXML {

	public static Map<String, ExceptionInfo> parseXML(String inputXml) throws XmlParseException {
		
		Map<String, ExceptionInfo> infos = new HashMap<String, ExceptionInfo>() ;
		try {
			SAXReader saxReader = new SAXReader();
			InputStream ins = ParseExpInfoXML.class.getResourceAsStream(inputXml) ;
			Document document = saxReader.read(ins);			
			
			Attribute attr = document.getRootElement().attribute("debug") ;
			if(attr != null) {
				ExceptionInfo.isExpDebug = Boolean.parseBoolean(attr.getValue()) ;
			}
			
			List elms = document.selectNodes("//exception") ;			
			Iterator it = elms.iterator() ;
			while(it.hasNext()) {
				Element elm = (Element)it.next() ;
				String name = elm.attribute("name").getValue() ;
				Node node1 = elm.selectSingleNode("./messagecode") ;
				Node node2 = elm.selectSingleNode("./loggingtype") ;
				Node node3 = elm.selectSingleNode("./forwardURL") ;
				Node node4 = elm.selectSingleNode("./contextind") ;				
				String msgcode = (node1!=null)?node1.getStringValue():null ;
				String logtype = (node2!=null)?node2.getStringValue():null ;
				String forwURL = (node3!=null)?node3.getStringValue():null ;
				String _context = (node4!=null)?node4.getStringValue():null ;
				boolean context = (_context!=null) ;
				ExceptionInfo info = new ExceptionInfo(msgcode, context, logtype, forwURL);				
				infos.put(name, info);				
			}			
		} catch (Exception e) {
			throw new XmlParseException("XML 解析错误!") ;
		}
		
		return infos ;
	}
	
	
	public static void main(String[] args) {		
		
		parseXML("/expinfo.xml") ;
	}

}
